<template>
  <picker class="warning-input" mode="multiSelector" :range="dateTimeArray" :value="dateValue" @change="change"
          @columnchange="columnchange">
    <view class="inp-box">
      <input type="text" disabled="true" v-model="dateTimeValue" :placeholder="text"
             placeholder-class="inputPlace"/>
    </view>
  </picker>
</template>

<script>
export default {
  name: 'u-datetime-picker',
  props: {
    text: {
      type: String,
      default: '请选择时间'
    },
  },
  data() {
    return {
      dateTimeArray: [],
      dateTime: [],
      dateTimeValue: '',
      dateValue: {},
    };
  },
  mounted() {
    let date = new Date(),
        Y = date.getFullYear() + '/',
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/',
        D = date.getDate() + ' ',
        h = '10' + ':'
    let arr = Y + M + D + h

    let obj = this.dateTimePicker(date.getFullYear(), this.endYear, arr)
    this.dateTimeArray = obj.dateTimeArray
    this.dateTime = obj.dateTime
    this.dateValue = [0, date.getMonth(), date.getDate() - 1, date.getHours()]

    this.dateTimeValue =
        `${date.getFullYear()}-${this.withData(date.getMonth() + 1)}-${this.withData(date.getDate())} ${this.withData(date.getHours())}`
  },
  methods: {
    change(e) {
      let value = []
      e.detail.value.forEach((val, index) => {
        value.push(val)
      })

      let time = this.dateTimeArray[0][value[0]] + "-" + this.dateTimeArray[1][value[1]] + "-" + this
              .dateTimeArray[2][value[2]] +
          " " + this.dateTimeArray[3][value[3]]
      this.dateTimeValue = time
      this.$emit("timeChange", this.dateTimeValue)
    },
    columnchange(e) {
      let dateArr = this.dateTimeArray
      let arr = this.dateTime
      //滑动所在列的数据并对其值进行更新
      arr[e.detail.column] = e.detail.value
      //更新展示月份对应的天数（28 or 29 or 30 or 31）
      dateArr[2] = this.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]])
      //最后把最新的数值赋值到dateTimeArray
      this.dateTimeArray = dateArr
      this.dateTime = arr
    },
    withData(param) {
      return param < 10 ? '0' + param : '' + param;
    },
    getLoopArray(start, end) {
      var start = start || 0;
      var end = end || 1;
      var array = [];
      for (var i = start; i <= end; i++) {
        array.push(this.withData(i));
      }
      return array;
    },
    getMonthDay(year, month) {
      var flag = year % 400 == 0 || (year % 4 == 0 && year % 100 != 0),
          array = null;

      switch (month) {
        case '01':
        case '03':
        case '05':
        case '07':
        case '08':
        case '10':
        case '12':
          array = this.getLoopArray(1, 31)
          break;
        case '04':
        case '06':
        case '09':
        case '11':
          array = this.getLoopArray(1, 30)
          break;
        case '02':
          array = flag ? this.getLoopArray(1, 29) : this.getLoopArray(1, 28)
          break;
        default:
          array = '月份格式不正确，请重新输入！'
      }
      return array;
    },
    getNewDateArry() {
      // 当前时间的处理 年月日时分秒
      var newDate = new Date();
      var year = this.withData(newDate.getFullYear()),
          mont = this.withData(newDate.getMonth() + 1),
          date = this.withData(newDate.getDate()),
          hour = this.withData(newDate.getHours()),
          minu = this.withData(newDate.getMinutes()),
          seco = this.withData(newDate.getSeconds());
      return [year, mont, date, hour, minu, seco];
    },
    dateTimePicker(startYear, endYear, date) {
      // 返回默认显示的数组和联动数组的声明
      var dateTime = []
      let dateTimeArray = [
        [],
        [],
        [],
        [],
      ];
      var start = startYear || 1978;
      var end = endYear || 2100;

      //处理传过来的字符串转化为数组
      let dataArr = date.split(" ")[0].split('/')
      let time = date.split(" ")[1].split(':')
      // 默认开始显示数据 如果把自定义值传过来的话就使用自定义时间 否则用当前时间  ...dataArr数组解构
      var defaultDate = date ? [...dataArr, ...time] : getNewDateArry();

      // 处理联动列表数据
      /*年月日 时分秒*/
      dateTimeArray[0] = this.getLoopArray(start, end);
      dateTimeArray[1] = this.getLoopArray(1, 12);
      dateTimeArray[2] = this.getMonthDay(defaultDate[0], defaultDate[1]);
      dateTimeArray[3] = this.getLoopArray(0, 23);

      //遍历dateTimeArray数组
      dateTimeArray.forEach((current, index) => {
        //匹配defaultDate[index]值在current数组中的位置
        dateTime.push(current.indexOf(defaultDate[index]))
      });

      return {
        dateTimeArray: dateTimeArray,
        dateTime: dateTime
      }
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
